#!/bin/bash

# 分布式存储系统 - 总编译脚本
# 编译所有模块：chunkmaster 和 chunkserver

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== 分布式存储系统 - 总编译脚本 ===${NC}"
echo ""

# 获取脚本所在目录
SCRIPT_DIR=$(cd $(dirname $0); pwd)
echo -e "${YELLOW}编译目录: $SCRIPT_DIR${NC}"
echo ""

# 检查依赖
echo -e "${YELLOW}1. 检查编译依赖...${NC}"

# 检查CMake
if ! command -v cmake &> /dev/null; then
    echo -e "${RED}错误: 需要安装CMake${NC}"
    echo "macOS: brew install cmake"
    exit 1
fi

# 检查make
if ! command -v make &> /dev/null; then
    echo -e "${RED}错误: 需要安装make${NC}"
    echo "macOS: 通常已预装，或使用 xcode-select --install"
    exit 1
fi

# 检查gcc/g++
if ! command -v g++ &> /dev/null; then
    echo -e "${RED}错误: 需要安装C++编译器${NC}"
    echo "macOS: xcode-select --install"
    exit 1
fi

echo -e "${GREEN}✓ 编译依赖检查通过${NC}"
echo ""

# 编译chunkmaster
echo -e "${YELLOW}2. 编译ChunkMaster模块...${NC}"
cd "$SCRIPT_DIR/persistent_layer/chunkmaster/build"

if [ ! -f "Makefile" ]; then
    echo -e "${BLUE}生成CMake构建文件...${NC}"
    cmake .. || {
        echo -e "${RED}✗ CMake配置失败${NC}"
        exit 1
    }
fi

echo -e "${BLUE}编译ChunkMaster...${NC}"
make clean && make || {
    echo -e "${RED}✗ ChunkMaster编译失败${NC}"
    exit 1
}

# 检查编译结果
if [ -f "chunkmaster" ]; then
    echo -e "${GREEN}✓ ChunkMaster编译成功${NC}"
    chmod +x chunkmaster
else
    echo -e "${RED}✗ ChunkMaster可执行文件未生成${NC}"
    exit 1
fi

echo ""

# 编译chunkserver
echo -e "${YELLOW}3. 编译ChunkServer模块...${NC}"
cd "$SCRIPT_DIR/persistent_layer/chunkserver/build"

if [ ! -f "Makefile" ]; then
    echo -e "${BLUE}生成CMake构建文件...${NC}"
    cmake .. || {
        echo -e "${RED}✗ CMake配置失败${NC}"
        exit 1
    }
fi

echo -e "${BLUE}编译ChunkServer...${NC}"
make clean && make || {
    echo -e "${RED}✗ ChunkServer编译失败${NC}"
    exit 1
}

# 检查编译结果
if [ -f "chunkserver_server" ] && [ -f "chunkserver_client" ]; then
    echo -e "${GREEN}✓ ChunkServer编译成功${NC}"
    chmod +x chunkserver_server chunkserver_client
else
    echo -e "${RED}✗ ChunkServer可执行文件未生成${NC}"
    exit 1
fi

echo ""

# 回到根目录
cd "$SCRIPT_DIR"

# 显示编译结果
echo -e "${BLUE}=== 编译结果 ===${NC}"
echo "ChunkMaster: $(ls -l persistent_layer/chunkmaster/build/chunkmaster 2>/dev/null | awk '{print $5 " bytes"}')"
echo "ChunkServer: $(ls -l persistent_layer/chunkserver/build/chunkserver_server 2>/dev/null | awk '{print $5 " bytes"}')"
echo "ChunkClient: $(ls -l persistent_layer/chunkserver/build/chunkserver_client 2>/dev/null | awk '{print $5 " bytes"}')"

echo ""
echo -e "${GREEN}=== 所有模块编译完成 ===${NC}"
echo ""
echo -e "${YELLOW}可执行文件位置:${NC}"
echo "  ChunkMaster: persistent_layer/chunkmaster/build/chunkmaster"
echo "  ChunkServer: persistent_layer/chunkserver/build/chunkserver_server"
echo "  ChunkClient: persistent_layer/chunkserver/build/chunkserver_client"
echo ""
echo -e "${YELLOW}启动测试:${NC}"
echo "  ./test_complete_system.sh"
echo ""
echo -e "${GREEN}编译成功！${NC}" 